<!--
    卡片风格的文件上传组件，主要用于一些小文件的上传，暂不支持分组上传

    用法：<f7-complex-upload :params="{type:'avatar',dataKey:models.articleId}" operType="view" title="附件"></f7-complex-upload>

    备注：params，url后的请求参数，JSON格式，比如上面的 { dataKey: 'xx', type: 'company' }
        title：显示的标题;
        operType：操作类型，取值为new和view，new表示将会显示上传的按钮，view隐藏上传按钮
 -->
<template>
  <div>
    <f7-card style="margin-left: 0px; margin-right: 0px;">
      <f7-card-header>
        <span>{{ title }}</span>
        <span v-if="operType == 'new'">
          <f7-link href="#" sheet-open=".voice-sheet">
            <i class="f7-icons">mic</i>
          </f7-link>&nbsp;
          <f7-link href="#" @click="$refs.videoAction.open()">
            <i class="f7-icons">videocam</i>
          </f7-link>&nbsp;
          <f7-link href="#" @click="$refs.pictureAction.open()">
            <i class="f7-icons">camera_round</i>
          </f7-link>
        </span>
      </f7-card-header>
      <f7-card-content class="f7-file-list">
        <f7-list media-list>
          <f7-list-item v-for="(file) in files" :key="file.attachmentId">
            <f7-link @click="operate(file)">
              <div class="f7-file-img pdf" v-if="file.fileType=='.pdf'"></div>
              <div
                class="f7-file-img ppt"
                v-else-if="file.fileType=='.ppt' || file.fileType=='.pptx'"
              ></div>
              <div
                class="f7-file-img docx"
                v-else-if="file.fileType=='.doc' || file.fileType=='.docx'"
              ></div>
              <div
                class="f7-file-img xls"
                v-else-if="file.fileType=='.xls' || file.fileType=='.xlsx'"
              ></div>
              <div
                class="f7-file-img pics"
                v-else-if="file.fileType=='.jpg' || file.fileType=='.png' || file.fileType=='.gif'"
              ></div>
              <div class="f7-file-img mp4" v-else-if="file.fileType=='.amr'"></div>
              <div class="f7-file-img audio" v-else-if="file.fileType=='.mp4'"></div>
              <div class="f7-file-img other" v-else></div>

              <div class="f7-file-title">
                {{file.fileName.split(".")[0].substr(0,3)+'...'}}
                {{file.fileName.split(".")[0].substr(file.fileName.split(".")[0].length-2) }}
                {{'.'+file.fileName.split(".")[1]}}
              </div>
              <div class="f7-file-fileSize">{{Math.ceil(file.fileSize/1024/1024)}}MB</div>
            </f7-link>
            <div class="deleteBtn" v-if="operType == 'new'">
              <f7-link @click.stop="deleteThis(file)">删除</f7-link>
            </div>
          </f7-list-item>
        </f7-list>
      </f7-card-content>
    </f7-card>

    <f7-actions ref="pictureAction">
      <f7-actions-group>
        <f7-actions-label>上传图片</f7-actions-label>
        <f7-actions-button @click="cameraPicture">拍照</f7-actions-button>
        <f7-actions-button @click="selectPicture">从相册选择</f7-actions-button>
        <f7-actions-button color="red">取消</f7-actions-button>
      </f7-actions-group>
    </f7-actions>

    <f7-actions ref="videoAction">
      <f7-actions-group>
        <f7-actions-label>上传视频</f7-actions-label>
        <f7-actions-button @click="cameraVideo">拍摄</f7-actions-button>
        <f7-actions-button @click="selectVideo">选择视频</f7-actions-button>
        <f7-actions-button color="red">取消</f7-actions-button>
      </f7-actions-group>
    </f7-actions>

    <f7-sheet class="voice-sheet" style="height:auto; background: #fff;" swipe-to-close backdrop>
      <f7-page-content>
        <f7-block class="text-align-center">
          <p v-if="!isVoice">长按说话</p>
          <p v-else>正在录音：{{ timeFormat }}</p>
          <p>
            <img id="voiceImg" :src="voiceimgUrl" style="width: 100px; height: 100px;" />
          </p>
        </f7-block>
      </f7-page-content>
    </f7-sheet>

    <div class="rank-promotion">
      <div class="content">
        <div class="rank-img">
          <img :src="voicePlaying" width="130px" alt />
        </div>
        <h4>语音播放中...</h4>
        <i @click="closeDialog">
          <img :src="closeImg" width="20px" alt />
        </i>
      </div>
    </div>
  </div>
</template>
<script>
import formatter from "@/libs/framework/formatter";
import Config from "@/libs/config";
import Upload from "@/libs/framework/upload";
import Util from "@/libs/framework/util";
import VoiceimgUrl from "@/assets/img/component/canclerecord.png";
import VoicePlaying from "@/assets/img/component/record.gif";
import CloseImg from "@/assets/img/component/close.png";

export default {
  props: {
    params: {
      type: Object,
      default: {}
    },
    extensions: {
      type: String
    },
    accept: {
      type: String
    },
    multiple: {
      type: Boolean,
      default: true
    },
    size: {
      type: Number,
      default: 1024 * 1024 * 10
    },
    operType: {
      default: "new", // new, view
      type: String
    },
    // postAction: {
    //   type: String,
    //   default: "/api/base/FileUpload/uploadFile"
    // },
    chunkAction: {
      type: String,
      default: "/api/base/ChunkUpload/upload"
    },
    uploadAuto: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      postAction: "/api/base/fileupload/uploadFile",
      downUrl: "/api/base/fileupload/downFile",
      getUrl: "/api/base/fileupload/getFiles",
      deleteUrl: "/api/base/fileupload/delFile",
      tasks: [],
      files: [],
      voiceimgUrl: "",
      recorder: null,
      isPlayAudio: false,
      voicePlaying: "",
      closeImg: "",
      isVoice: false, //是否录音
      touchstartY: "", //手指刚开始触摸的屏幕Y坐标
      touchmoveY: "", //手指移动触摸的屏幕X坐标
      timeSecond: 0, //时间秒数
      showVoiceImg: false, //显示录音图标
      voiceMsg: "", //录音显示的文字
      isCancel: false, //是否取消录音
      isRecord: false, //是否录音进行中
      voicePath: "", //录音文件的路径
      warning: null
    };
  },
  created() {
    this.$f7.request.post(this.getUrl, this.params, r => {
      r = JSON.parse(r);
      if (r && r.success) {
        this.files = r.parameters.files || [];
      } else {
        this.$f7.dialog.toast("获取文件失败");
      }
    });
  },
  computed: {
    isPlus() {
      return window.plus != undefined;
    },
    timeFormat() {
      let result = parseInt(this.timeSecond);
      let h =
        Math.floor(result / 3600) < 10
          ? "0" + Math.floor(result / 3600)
          : Math.floor(result / 3600);
      let m =
        Math.floor((result / 60) % 60) < 10
          ? "0" + Math.floor((result / 60) % 60)
          : Math.floor((result / 60) % 60);
      let s =
        Math.floor(result % 60) < 10
          ? "0" + Math.floor(result % 60)
          : Math.floor(result % 60);
      result = `${h}:${m}:${s}`;
      return result;
    }
  },
  mounted() {
    this.closeImg = CloseImg;
    this.voicePlaying = VoicePlaying;
    this.voiceimgUrl = VoiceimgUrl;
    let self = this;
    self.$f7.$("div.rank-promotion").hide();
    if (window.plus) {
      this.postAction = Config.api.upload;
      this.downUrl = Config.api.download;

      self.recorder = window.plus.audio.getRecorder();

      this.$f7.$("#voiceImg").on("touchstart", function(e) {
        self.isCancel = false;
        self.isRecord = false;
        self.isVoice = true;
        self.voicePath = "";
        if (self.isVoice) {
          self.audioClick(e);
          e.preventDefault();
        }
      });
      this.$f7.$("#voiceImg").on("touchend", function(e) {
        self.stopRecord();
      });
      this.$f7.$("#voiceImg").on("touchcancel", function(e) {
        self.stopRecord();
      });

      this.$f7.$("#voiceImg").on("touchmove", function(e) {
        if (self.isVoice) {
          self.touchmoveY = e.changedTouches[0].screenY; //不断监听下拉过程中手指的位置
          if (self.touchstartY - self.touchmoveY >= 150) {
            self.isRecord = true;
            self.voiceMsg = "松开手指取消录音";
            self.isCancelisCancel = true;
          } else if (self.touchstartY - self.touchmoveY < 150) {
            self.voiceMsg = "正在录音，松手上传";
            self.isRecord = false;
            self.isCancel = false;
          }
        }
      });

      self.isVoice = false;
      self.touchstartY = ""; //手指刚开始触摸的屏幕Y坐标
      self.touchmoveY = ""; //手指移动触摸的屏幕X坐标
      self.timeSecond = 0; //时间秒数
      self.voiceMsg = "";
    }
  },
  methods: {
    audioClick(e) {
      // this.isVoice = true;
      let self = this;
      var dialog = self.$f7.dialog;
      self.touchstartY = e.changedTouches[0].screenY;
      if (self.recorder == null) {
        dialog.toast("不支持录音失败");
        return;
      }
      // 先停止
      self.recorder.stop();
      self.timeSecond = 0;
      // window.plus.device.beep(1);
      self.showVoiceImg = true;
      self.voiceMsg = "正在录音，松手上传";
      var timeId = window.setInterval(function() {
        self.timeSecond++;
      }, 1000);
      self.recorder.record(
        {
          filename: "_doc/audio/",
          format: "amr"
        },
        function(p) {
          window.clearInterval(timeId);
          self.voicePath = p;
          if (vue.$f7.device.ios) {
            self.voicePath = "file://" + p;
          }
          if (!self.isCancel && self.timeSecond > 0) {
            self.upload(p, self.params.dataKey, self.params.type);
          }
        },
        function(e) {
          window.clearInterval(timeId);
          self.showVoiceImg = false;
          dialog.toast("录音失败:" + JSON.stringify(e));
        }
      );
    },
    //停止录音
    stopRecord() {
      let self = this;
      if (self.isVoice) {
        self.recorder.stop();
        self.isVoice = false;
        self.showVoiceImg = false;
        if (self.timeSecond < 1 || self.isCancel) {
          if (self.voicePath != "" && self.voicePath != undefined) {
            //删除无用的文件
            Upload.deleteTmpFile(self.voicePath);
          }
          if (self.timeSecond < 1) {
            self.$f7.dialog.toast("最少需要满两秒");
            self.voicePath = "";
            self.showVoiceImg = false;
            self.isRecord = false;
            self.isCancel = false;
            // return;
          }
        }

        let sheet = this.$f7.sheet.get(".voice-sheet");
        if (sheet) {
          sheet.close();
        }
      }
    },
    deleteThis(file) {
      this.$f7.dialog.confirm("该文件已上传成功，确定要删除嘛？", r => {
        if (r) {
          this.$f7.request.post(
            this.deleteUrl,
            { attachmentId: file.attachmentId },
            r => {
              r = JSON.parse(r);
              if (r && r.success) {
                this.files.splice(this.files.indexOf(file), 1);
                this.$f7.dialog.toast("文件删除成功");
              } else {
                this.$f7.dialog.toast("文件删除失败");
              }
            },
            e => {
              this.$f7.dialog.toast("文件删除失败");
            }
          );
        }
      });
    },
    upload(filePath, dataKey, type) {
      if (!Util.isString(filePath)) {
        return;
      }

      let filename = filePath.substr(filePath.lastIndexOf("/") + 1);

      // let wt = window.plus.nativeUI.showWaiting();
      // 上传必须是全路径
      let server = Config.api.upload;

      let self = this;

      let task = window.plus.uploader.createUpload(
        server,
        { method: "POST" },
        function(t, status) {
          //上传完成
          if (status == 200) {
            // TODO 可能有问题
            let filesJSON = JSON.parse(t.responseText);

            self.files.push({
              attachmentId: filesJSON.files[0].key,
              fileName: filesJSON.files[0].name,
              fileSize: filesJSON.files[0].size
            });

            window.plus.nativeUI.closeWaiting();
          } else {
            console.error("上传失败：" + status);
            window.plus.nativeUI.closeWaiting();
          }
        }
      );

      this.tasks.push(task);

      task.addEventListener(
        "statechanged",
        function(upload, status) {
          if (status === undefined) {
            console.log("上传任务未开始");
          } else if (status === 0) {
            // console.log("上传任务开始调度");
            self.showWarning(
              "上传中..." +
                Math.round((task.uploadedSize / task.totalSize) * 100) +
                "%"
            );
          } else if (status === 1) {
            console.log("上传任务开始请求");
          } else if (status === 2) {
            console.log("上传任务请求已经建立");
            self.showWarning("链接到服务器...");
          } else if (status === 3) {
            console.log("上传任务提交数据");
            // 更新进度
          } else if (status === 4) {
            console.log("上传任务已完成");
            self.showWarning("上传完成！");
          } else if (status === 5) {
            console.log("上传任务已暂停");
          }
        },
        false
      );

      console.log(`上传文件的路径：${filePath}`);
      console.log(`添加参数<-文件类型-> ：${task.addData("type", type)}`);
      // 文件名，解决后台接收到的中文文件名乱码
      console.log(
        `添加参数<-文件名称-> ：${task.addData("filename", filename)}`
      );
      console.log(`添加参数<-业务主键-> ：${task.addData("dataKey", dataKey)}`);
      console.log(
        `添加参数<-目标文件-> ：${task.addFile(filePath, { key: "file" })}`
      );

      task.start();
    },
    cameraVideo() {
      if (!this.isPlus) {
        console.log("不是手机端，无法操作");
        return;
      }
      let self = this;
      let cmr = window.plus.camera.getCamera();
      //设置像素
      let res = cmr.supportedVideoResolutions[0];
      let fmt = cmr.supportedVideoFormats[0];
      cmr.startVideoCapture(
        p => {
          window.plus.io.resolveLocalFileSystemURL(
            p,
            entry => {
              let path = entry.fullPath;
              if (vue.$f7.device.ios) {
                path = "file://" + path;
              }
              self.upload(path, self.params.dataKey, self.params.type);
            },
            e => {
              console.log("读取录像文件错误：" + e.message);
            }
          );
        },
        function(e) {
          console.log("失败：" + e.message);
        },
        {
          filename: "_doc/video/",
          index: 1, // 1表示主摄像头，2表示辅摄像头。
          resolution: res,
          format: fmt
        }
      );
    },
    selectVideo() {
      if (!this.isPlus) {
        console.log("不是手机端，无法操作");
        return;
      }
      let self = this;
      console.log("选择视频文件：");
      window.plus.gallery.pick(
        function(entry) {
          for (let i in entry.files) {
            let path = entry.files[i] + "";
            let fileType = path.substr(path.lastIndexOf("."));
            if (self.isVideo(fileType)) {
              self.upload(
                entry.files[i],
                self.params.dataKey,
                self.params.type
              );
            }
          }
        },
        function(e) {
          console.log("取消选择视频");
        },
        {
          filter: "video",
          multiple: true
        }
      );
    },
    cameraPicture() {
      if (!this.isPlus) {
        console.log("不是手机端，无法操作");
        return;
      }
      console.log("开始拍照：");
      let self = this;
      let filename = "_doc/" + "camera/" + Util.random() + ".jpg";
      let cmr = window.plus.camera.getCamera();
      cmr.captureImage(
        function(p) {
          console.log("成功：" + p);
          window.plus.io.resolveLocalFileSystemURL(
            p,
            function(entry) {
              let path = entry.fullPath;
              if (self.$f7.device.ios) {
                path = "file://" + entry.fullPath;
              }
              self.upload(path, self.params.dataKey, self.params.type);
            },
            function(e) {
              console.error("读取拍照文件错误：" + e.message);
            }
          );
        },
        function(e) {
          console.error("失败：" + e.message);
        },
        {
          filename: filename,
          index: 1
        }
      );
    },
    selectPicture() {
      if (!this.isPlus) {
        console.log("不是手机端，无法操作");
        return;
      }
      let self = this;
      console.log("从相册中选择图片：");
      window.plus.gallery.pick(
        function(entry) {
          for (let i in entry.files) {
            self.upload(
              entry.files[i],
              self.params.dataKey,
              self.params.type,
              "IMAGE"
            );
          }
        },
        function(e) {
          console.log("取消选择图片");
        },
        {
          filter: "image",
          multiple: true
        }
      );
    },

    isImage(fileType) {
      let lowType = fileType.toLowerCase();
      return ".jpg,.jpeg,.gif,.bmp,.png".indexOf(lowType) > -1;
    },
    isVideo(fileType) {
      let lowType = fileType.toLowerCase();
      return ".mp4,.flv,.m3u8,.mov,.mvk,.wmv,.avi,.mpg".indexOf(lowType) > -1;
    },
    isAudio(fileType) {
      let lowType = fileType.toLowerCase();
      return ".amr,.3gp,.wav,.aac".indexOf(lowType) > -1;
    },
    isPdf(fileType) {
      let lowType = fileType.toLowerCase();
      return ".pdf,.PDF".indexOf(lowType) > -1;
    },

    operate(file) {
      let self = this;
      let fileType = file.fileName.substr(file.fileName.lastIndexOf("."));
      if (this.isImage(fileType)) {
        // 图片
        if (this.isPlus) {
          var store = window.plus.storage.getItem(file.attachmentId);
          var successCallback = function(filename) {
            if (self.$f7.device.ios) {
              // 坑2：ios的，前面要加file://，不然找不到文件
              window.plus.runtime.openFile(
                decodeURI(
                  "file://" + window.plus.io.convertLocalFileSystemURL(filename)
                ),
                {},
                function(error) {
                  self.$f7.dialog.toast(error.message);
                }
              );
            } else {
              window.plus.runtime.openFile(
                window.plus.io.convertLocalFileSystemURL(filename),
                {},
                function(error) {
                  self.$f7.dialog.toast(error.message);
                }
              );
            }
          };
          if (this.isValidFilepath(store)) {
            plus.io.resolveLocalFileSystemURL(
              store,
              function(entry) {
                entry.file(function(file) {
                  successCallback(store);
                });
              },
              function() {
                self.ensureDownload(
                  file.attachmentId,
                  file.fileName,
                  file.fileSize,
                  successCallback
                );
              }
            );
          } else {
            self.ensureDownload(
              file.attachmentId,
              file.fileName,
              file.fileSize,
              successCallback
            );
          }
        } else {
          let photos = [];
          photos.push({
            url: this.downUrl + "?attachmentId=" + file.attachmentId,
            caption: file.fileName
          });
          let photoBrowser = this.$f7.photoBrowser.create({
            photos: photos,
            type: "popup",
            swipeToClose: false
          });
          photoBrowser.open(0);
          photoBrowser.on("closed", () => {
            photoBrowser.destroy();
          });
        }
      } else if (this.isVideo(fileType)) {
        var store = window.plus.storage.getItem(file.attachmentId);
        var successCallback = function(filename) {
          if (self.$f7.device.ios) {
            // 坑2：ios的，前面要加file://，不然找不到文件
            window.plus.runtime.openFile(
              decodeURI(
                "file://" + window.plus.io.convertLocalFileSystemURL(filename)
              ),
              {},
              function(error) {
                if (error.message.indexOf("not found 3th activity") == -1) {
                  self.$f7.dialog.toast(error.message);
                } else {
                  self.$f7.dialog.toast("暂未找到可以打开该文件的软件！");
                }
              }
            );
          } else {
            window.plus.runtime.openFile(
              window.plus.io.convertLocalFileSystemURL(filename),
              {},
              function(error) {
                if (error.message.indexOf("not found 3th activity") == -1) {
                  self.$f7.dialog.toast(error.message);
                } else {
                  self.$f7.dialog.toast("暂未找到可以打开该文件的软件！");
                }
              }
            );
          }
        };
        if (this.isValidFilepath(store)) {
          plus.io.resolveLocalFileSystemURL(
            store,
            function(entry) {
              entry.file(function(file) {
                successCallback(store);
                // window.plus.runtime.openFile(store);
              });
            },
            function() {
              self.ensureDownload(
                file.attachmentId,
                file.fileName,
                file.fileSize,
                successCallback
              );
            }
          );
        } else {
          self.ensureDownload(
            file.attachmentId,
            file.fileName,
            file.fileSize,
            successCallback
          );
        }
      } else if (this.isAudio(fileType)) {
        // 语音
        if (this.isPlus) {
          this.playAudio(file);
        } else {
          this.$f7.dialog.toast("不是手机端");
        }
      } else if (this.isPdf(fileType)) {
        var successCallback = function(filename) {
          if (self.$f7.device.ios) {
            // 坑1：ios的，请确保filename不是乱码的(有可能下载下来的就是乱码的)，不然找不到文件
            self.$f7.views.current.router.navigate(
              "/business/file/fileView?path=" +
                decodeURI(window.plus.io.convertLocalFileSystemURL(filename))
            );
          } else {
            self.$f7.views.current.router.navigate(
              "/business/file/fileView?path=" +
                window.plus.io.convertLocalFileSystemURL(filename)
            );
          }
        };
        var store = window.plus.storage.getItem(file.attachmentId);
        if (this.isValidFilepath(store)) {
          plus.io.resolveLocalFileSystemURL(
            store,
            function(entry) {
              entry.file(function(file) {
                successCallback(store);
              });
            },
            function() {
              self.ensureDownload(
                file.attachmentId,
                file.fileName,
                file.fileSize,
                successCallback
              );
            }
          );
        } else {
          self.ensureDownload(
            file.attachmentId,
            file.fileName,
            file.fileSize,
            successCallback
          );
        }
      } else {
        var store = window.plus.storage.getItem(file.attachmentId);
        var successCallback = function(filename) {
          if (self.$f7.device.ios) {
            // 坑2：ios的，前面要加file://，不然找不到文件
            window.plus.runtime.openFile(
              decodeURI(
                "file://" + window.plus.io.convertLocalFileSystemURL(filename)
              ),
              {},
              function(error) {
                if (error.message.indexOf("not found 3th activity") == -1) {
                  self.$f7.dialog.toast(error.message);
                } else {
                  self.$f7.dialog.toast("暂未找到可以打开该文件的软件！");
                }
              }
            );
          } else {
            window.plus.runtime.openFile(
              window.plus.io.convertLocalFileSystemURL(filename),
              {},
              function(error) {
                if (error.message.indexOf("not found 3th activity") == -1) {
                  self.$f7.dialog.toast(error.message);
                } else {
                  self.$f7.dialog.toast("暂未找到可以打开该文件的软件！");
                }
              }
            );
          }
        };
        if (this.isValidFilepath(store)) {
          plus.io.resolveLocalFileSystemURL(
            store,
            function(entry) {
              entry.file(function(file) {
                successCallback(store);
              });
            },
            function() {
              self.ensureDownload(
                file.attachmentId,
                file.fileName,
                file.fileSize,
                successCallback
              );
            }
          );
        } else {
          self.ensureDownload(
            file.attachmentId,
            file.fileName,
            file.fileSize,
            successCallback
          );
        }
      }
    },

    playAudio(file) {
      let self = this;

      if (window.plus.audio == undefined) {
        self.$f7.dialog.toast("不支持语音播放");
        return;
      }
      if (self.audio != null) {
        self.isPlayAudio = false;
        self.audio.stop();
      }

      var store = window.plus.storage.getItem(file.attachmentId);

      var successCallback = function(path) {
        self.audio = window.plus.audio.createPlayer(path);
        self.isPlayAudio = true;

        self.$f7.dialog
          .create({
            el: self.$f7.$("div.rank-promotion"),
            destroyOnClose: true,
            title: "",
            text: "",
            content: ""
          })
          .open();
        self.$f7.$("div.rank-promotion").show();

        self.audio.play(
          function() {
            self.isPlayAudio = false;
            self.closeDialog();
          },
          function(e) {
            self.isPlayAudio = false;
            self.$f7.dialog.toast("播放失败: " + e.message);
          }
        );
      };

      if (this.isValidFilepath(store)) {
        plus.io.resolveLocalFileSystemURL(
          store,
          function(entry) {
            entry.file(function(file) {
              successCallback(store);
            });
          },
          function() {
            self.createDownload(
              file.attachmentId,
              file.fileName,
              successCallback
            );
          }
        );
      } else {
        self.createDownload(file.attachmentId, file.fileName, successCallback);
      }
    },
    closeDialog() {
      let dialog = this.$f7.dialog.get("div.rank-promotion");
      if (dialog) {
        dialog.close();
      }
      this.$f7.$("div.rank-promotion").hide();
      if (self.audio) {
        self.audio.stop();
      }
    },

    ensureDownload(attachmentId, filename, size, successCallback) {
      let self = this;
      if (window.plus.networkinfo.getCurrentType() != 3) {
        self.$f7.dialog.confirm(
          "当前不在wifi模式下，继续将使用" +
            Math.ceil(size / 1024 / 1024) +
            "MB流量，是否继续？",
          r => {
            if (r) {
              self.createDownload(attachmentId, filename, successCallback);
            }
          }
        );
      } else {
        self.createDownload(attachmentId, filename, successCallback);
      }
    },
    // 创建下载任务
    createDownload(attachmentId, filename, successCallback) {
      let self = this;
      var dtask = window.plus.downloader.createDownload(
        Config.api.download + "?attachmentId=" + attachmentId,
        { filename: `_downloads/${filename}` }, // 坑3：这里指定下载的文件路径（包括文件名），如果不指定，ios下载下来的可能是乱码的文件名
        function(d, status) {
          // 下载完成
          if (
            status == 200 &&
            d.filename.indexOf("downFile") == -1 &&
            d.filename.indexOf("login") == -1
          ) {
            let filePath = window.plus.io.convertLocalFileSystemURL(d.filename);
            window.plus.storage.setItem(attachmentId, decodeURI(d.filename));
            if (successCallback) {
              successCallback(decodeURI(d.filename));
            }
            // window.plus.runtime.openFile(
            //   filePath
            // );
            window.plus.nativeUI.closeWaiting();
          } else {
            self.$f7.dialog.toast("文件加载异常，由于: " + status);
            window.plus.nativeUI.closeWaiting();
          }
        }
      );
      dtask.addEventListener("statechanged", function(task, status) {
        if (!dtask) {
          return;
        }
        switch (task.state) {
          case 1:
            self.showWarning("开始加载...");
            break;
          case 2:
            self.showWarning("链接到服务器...");
            break;
          case 3:
            self.showWarning(
              "加载中..." +
                Math.round((task.downloadedSize / task.totalSize) * 100) +
                "%"
            );
            break;
          case 4:
            self.showWarning("加载完成，正在打开...");
            break;
        }
      });
      dtask.start();
    },
    showWarning(message) {
      let self = this;
      if (self.warning) {
        self.warning.setTitle(message);
      } else {
        self.warning = window.plus.nativeUI.showWaiting(message);
        self.warning.onclose = function() {
          self.warning = null;
        };
      }
    },
    // 是否是合法的文件名称
    isValidFilepath(filepath) {
      return (
        filepath != null &&
        filepath.length > 5 &&
        filepath.indexOf(".") > 0 &&
        filepath.indexOf("downFile") == -1 &&
        filepath.indexOf("login") == -1
      );
    },

    // 申请权限
    requestAudioPermission() {
      // let sheet = vue.$f7.sheet.get(".voice-sheet");
      // if (sheet) {
      //   sheet.open();
      // }
      // return new Promise((resolve, reject) => {
      //   if (vue.$f7.device.android) {
      //     window.plus.android.requestPermissions(
      //       ["android.permission.RECORD_AUDIO"],
      //       function(e) {
      //         if (e.deniedAlways.length > 0) {
      //           //权限被永久拒绝
      //           console.log("Always Denied!!! " + e.deniedAlways.toString());
      //           vue.$f7.dialog.alert(
      //             "麦克风已被永久拒绝使用，请在【设置】-> 【应用】里设置允许App使用麦克风！"
      //           );
      //           resolve(false);
      //         }
      //         if (e.deniedPresent.length > 0) {
      //           //权限被临时拒绝
      //           console.log("Present Denied!!! " + e.deniedPresent.toString());
      //           vue.$f7.dialog.alert("麦克风已被拒绝使用，无法使用录音功能");
      //           resolve(false);
      //         }
      //         if (e.granted.length > 0) {
      //           //权限被允许
      //           console.log("Granted!!! " + e.granted.toString());
      //           let sheet = vue.$f7.sheet.get(".voice-sheet");
      //           if (sheet) {
      //             sheet.open();
      //           }
      //           resolve(true);
      //         }
      //       },
      //       function(e) {
      //         console.log("Request Permissions error:" + JSON.stringify(e));
      //       }
      //     );
      //   } else {
      //     resolve(true);
      //   }
      // });
    }
  }
};
</script>
<style scoped>
.card {
  box-shadow: none;
}

.card-header > span {
  /* color: #333333; */
  font-weight: bold;
  /* font-size: 18px; */
}

.card-header a.link {
  padding: 0 5px;
}

.card-header a.link i {
  font-size: 22px;
}

.chunk-loading {
  margin: -12px;
  display: flex;
  width: calc(100% + 24px);
}

.chunk-loading .chunk-loading-part {
  height: 25px;
  line-height: 25px;
  flex: 1;
  background: #ccc;
  font-size: 14px;
  color: white;
  text-align: center;
}

.chunk-loading .chunk-loading-part.chunk-loading-part__uploaded {
  /* background: #28a745; */
}

.file-uploads {
  width: 100%;
}
</style>